/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import httpclient from '@ohos/httpclient';
import Log from '../../log/log';
import router from '@system.router';

export default {
    data: {
        status: "",
        content: "",
        echoServer: "http://www.yourserverfortest.com",
        redirectServer: "http://www.yourserverforredirect.com",
        client: new httpclient.HttpClient.Builder().setConnectTimeout(10000).build(),
        ws:""
    },

    onInit() {
    },

    showIndexView() {
        router.push({
            uri: 'pages/index/index'
        })
    },

    onComplete: function (result) {
        if (result.response) {
            this.status = result.response.responseCode;
        }
        if (result.response.result)
            this.content = result.response.result;
        else
            this.content = JSON.stringify(result.response);

        Log.showInfo("onComplete -> Status : " + this.status);
        Log.showInfo("onComplete -> Content : " + JSON.stringify(this.content));
    },

    onError: function (error) {
         this.status = "";
        this.content = error.data;
        Log.showInfo("onError -> Error : " + this.content);
    },

    sendGetRequest() {
        let request = new httpclient.Request.Builder()
            .get("https://postman-echo.com/get?foo1=bar1&foo2=bar2")
            .addHeader("Content-Type", "application/json")
            .params("testKey1", "testValue1")
            .params("testKey2", "testValue2")
            .build();

        this.client.newCall(request).enqueue(this.onComplete, this.onError);
    },

    sendPostRequest() {
        var request = new httpclient.Request.Builder()
            .url(this.echoServer)
            .post(httpclient.RequestBody.create("test123"))
            .addHeader("Content-Type", "application/json")
            .build();
        this.client.newCall(request).execute().then(this.onComplete).catch(this.onError);
    },

    sendPostRequest2() {
        var request = new httpclient.Request.Builder()
                .url("https://postman-echo.com/post")
                .post(httpclient.RequestBody.create({
                    a: 'a1', b: 'b1'
                }, new httpclient.Mime.Builder().contentType('application/json', 'charset', 'utf8').build().getMime()))
                .build();
        this.client.newCall(request).execute().then(this.onComplete).catch(this.onError);
    },

    sendPostRequest3() {
        let formEncoder = new httpclient.FormEncoder.Builder()
                .add('key1', 'value1')
                .add('key2', 'value2')
                .build();
        let feBody = formEncoder.createRequestBody();
        var request = new httpclient.Request.Builder()
                .url("https://postman-echo.com/post")
                .post(feBody)
                .build();
        this.client.newCall(request).execute().then(this.onComplete).catch(this.onError);
    },

    sendRedirectRequest() {
        var localClient = new httpclient.HttpClient.Builder()
            .setConnectTimeout(10000)
            .build();

        var request = new httpclient.Request.Builder()
            .get(this.redirectServer)
            .addHeader("Content-Type", "application/json")
            .followRedirects(true)
            .retryOnConnectionFailure(true)
            .redirectMaxLimit(20)
            .retryMaxLimit(20)
            .build();

        localClient.newCall(request)
            .execute()
            .then(this.onComplete)
            .catch(this.onError);
    },

    putRequest() {
        var request = new httpclient.Request.Builder()
                .url("https://postman-echo.com/put")
                .put(httpclient.RequestBody.create({
                    a: 'a1', b: 'b1'
                }, new httpclient.Mime.Builder().contentType('application/json', 'charset', 'utf8').build()))
                .build();
        this.client.newCall(request).execute().then(this.onComplete).catch(this.onError);
    },

    deleteRequest() {
        var request = new httpclient.Request.Builder()
                .url("https://reqres.in/api/users/2")
                .delete()
                .build();
        this.client.newCall(request).execute().then(this.onComplete).catch(this.onError);
    },

    multiDataRequest() {
        let requestBody1 = httpclient.RequestBody.create({Title: 'Multipart', Color: 'Brown'})
        let requestBody2 = httpclient.RequestBody.create("Okhttp")
        let requestBody3 = httpclient.RequestBody.create("MultiRequest")
        let boundary = "AaB03x";

        let multiPartObj = new httpclient.MultiPart.Builder()
                    .boundary(boundary)
                    .type(httpclient.MultiPart.FORMDATA)
                    .addPart(requestBody1)
                    .addPart(requestBody2)
                    .addPart(requestBody3)
                    .build();
        let body = multiPartObj.createRequestBody();
        var request =  new httpclient.Request.Builder()
            .url(this.echoServer)
            .post(body)
            .addHeader("Content-Type", "multipart/form-data")
            .params("LibName", "Okhttp-ohos")
            .params("Request", "MultiData")
            .build();
        this.client.newCall(request).enqueue(this.onComplete, this.onError);
    },

    multipleRequests() {
        //GET
        let request1 = new httpclient.Request.Builder()
            .get(this.echoServer)
            .addHeader("Content-Type", "application/json")
            .params("testKey1", "testValue1")
            .params("testKey2", "testValue2")
            .build();
        this.client.newCall(request1).enqueue(this.onComplete, this.onError);

        //POST
        let request2 = new httpclient.Request.Builder()
            .url(this.echoServer)
            .post(httpclient.RequestBody.create("test123"))
            .addHeader("Content-Type", "application/json")
            .build();
        this.client.newCall(request2).enqueue(this.onComplete, this.onError);

        //POST with 2 values
        let request3 = new httpclient.Request.Builder()
            .url(this.echoServer)
            .post(httpclient.RequestBody.create({
                a: 'a1', b: 'b1'
            }, new httpclient.Mime.Builder().contentType('application/json', 'charset', 'utf8').build().getMime()))
            .build();
        this.client.newCall(request3).enqueue(this.onComplete, this.onError);
        //POST with 3 values
        let formEncoder = new httpclient.FormEncoder.Builder()
            .add('key1', 'value1')
            .add('key2', 'value2')
            .add('key3', 'value3')
            .build();
        let feBody = formEncoder.createRequestBody();

        var request4 = new httpclient.Request.Builder()
            .url(this.echoServer)
            .post(feBody)
            .build();
        this.client.newCall(request4).enqueue(this.onComplete, this.onError);

        //PUT request
        var request5 = new httpclient.Request.Builder()
            .url(this.echoServer)
            .put(httpclient.RequestBody.create({
                    a: 'a1', b: 'b1'
                }, new httpclient.Mime.Builder().contentType('application/json', 'charset', 'utf8').build().getMime()))
            .build();
        this.client.newCall(request5).enqueue(this.onComplete, this.onError);

        //DELETE request
        var request6 = new httpclient.Request.Builder()
            .url(this.echoServer)
            .delete()
            .build();
        this.client.newCall(request6).enqueue(this.onComplete, this.onError);
    },

    newCallRequest() {
        var request = new httpclient.Request.Builder()
                .url("https://postman-echo.com/post")
            .post(httpclient.RequestBody.create("test123"))
            .addHeader("Content-Type", "application/json")
            .build();
        this.client.newCall(request).execute().then(this.onComplete).catch(this.onError);
    },

    onDNSRequest: function (req) {
        var route =new httpclient.Route(this.info);

        //Now we have got the interceptor, now we can connect to IPAddress one after the other if previous one fails
        Log.showInfo("onDNSRequest and route" + route);
        return req;
    },

    onDNSResponse: function (res) {

        return res;
    },

    useDNSInterceptor() {
        var url = "www.baidu.com";
        var request = new httpclient.Request.Builder()
            .get(url)
            .addInterceptor(this.onDNSRequest, this.onDNSResponse)
            .build();

        this.client.newCall(request).enqueue(this.onComplete, this.onError);
    },

    handleDNSInterceptor() {
        var url = "www.baidu.com";
        this.info = httpclient.DnsUtil.resolveDNSQuery(url);
        setTimeout(this.useDNSInterceptor, 3000); //execute useDNSInterceptor after 3000 milliseconds (3 seconds)
    }
}